package com.example.starseas_phone;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.starseas_phone.Adapters.CollegemanageAdapter;
import com.example.starseas_phone.Entity.College;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CollegemanageActivity extends AppCompatActivity {

    private FloatingActionButton collegemanage_floatbtn;
    private ListView collegemanage_list;
    private List<College> list = new ArrayList<>();
    private CollegemanageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collegemanage);
        initid();
        initfindcollege();
        collegemanage_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                College college = adapter.getItem(i);
                //首先添加一个edit实例，然后通过dialog设置显示
                final EditText editText = new EditText(CollegemanageActivity.this);
                AlertDialog.Builder dialog = new AlertDialog.Builder(CollegemanageActivity.this);
                dialog.setTitle("修改学院");
                dialog.setView(editText);
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updatecollegemanage(college,editText.getText().toString());
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.show();
                return false;
            }
        });
    }

    private void initid(){
        collegemanage_floatbtn = (FloatingActionButton) findViewById(R.id.collegemanage_floatbtn);
        collegemanage_list = (ListView) findViewById(R.id.collegemanage_list);
        adapter = new CollegemanageAdapter(CollegemanageActivity.this,R.layout.collegemanage_listview,list);
    }

    private void initfindcollege(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Sto.NetIP+"/api/College/GetAllCollege")
                            .get()
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseString = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseString);
                    String msg = jsonObject.getString("message");
                    JSONArray jsonArray = new JSONArray(msg);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObjects = jsonArray.getJSONObject(i);
                        String CollegeName = jsonObjects.getString("CollegeName");
                        int CollegeId = jsonObjects.getInt("CollegeId");
                        College college = new College(CollegeName,CollegeId);
                        list.add(college);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            collegemanage_list.setAdapter(adapter);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    protected void onStart() {
        super.onStart();
        collegemanage_floatbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //首先添加一个edit实例，然后通过dialog设置显示
                final EditText editText = new EditText(CollegemanageActivity.this);
                AlertDialog.Builder dialog = new AlertDialog.Builder(CollegemanageActivity.this);
                dialog.setTitle("添加学院");
                dialog.setView(editText);
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addcollegemanage(editText.getText().toString());
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.show();
            }
        });
    }

    private void addcollegemanage(String CollegeName){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody requestBody = RequestBody.create(mediaType,"");
                    Request request = new Request.Builder()
                            .url(Sto.NetIP+"/api/College/InsertCollege?CollegeName="+CollegeName)
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseString = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseString);
                    int code = jsonObject.getInt("code");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code==200){
                                Toast.makeText(CollegemanageActivity.this,"添加学院成功!",Toast.LENGTH_SHORT).show();
                                list.clear();
                                initfindcollege();
                            }else {
                                Toast.makeText(CollegemanageActivity.this,"添加学院失败!",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void updatecollegemanage(College college,String CollegeName){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    JSONObject jsonObjects = new JSONObject();
                    jsonObjects.put("CollegeId",college.getCollegeId());
                    jsonObjects.put("CollegeName",CollegeName);
                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody requestBody = RequestBody.create(mediaType,jsonObjects.toString()+"");
                    Request request = new Request.Builder()
                            .url(Sto.NetIP+"/api/College/UpdateCollege")
                            .put(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseString = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseString);
                    String message = jsonObject.getString("message");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(CollegemanageActivity.this,message+"!",Toast.LENGTH_SHORT).show();
                            list.clear();
                            initfindcollege();
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

}